<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('编辑')" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'560px':'720px'" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90" style="margin:0 30px;">
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'150px':'240px'" :rules="rules" label-position="left">
        <el-form-item :label="$t('策略模块名称')" prop="state">
          {{ $t(modeNameArray[record.name]) }}
        </el-form-item>
        <el-form-item :label="$t('监控策略状态')" prop="state">
          <el-radio-group v-model="record.state">
            <el-radio label="enable" class="enable">{{$t('启用')}}</el-radio>
            <el-radio label="disable" class="disable">{{$t('禁用')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('告警阀值')" prop="threshold" v-if="record.name !== 'sys-manager' && record.name !== 'interface'">
          <el-input v-emoji v-model="record.threshold" ref="threshold" :disabled='record.state === "disable"' style="width:272px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('告警严重等级')" prop="severity">
          <el-radio-group v-model="record.severity" :disabled='record.state === "disable"'>
            <el-radio label="critical" class="critical">{{$t('紧急')}}</el-radio>
            <el-radio label="major" class="major">{{$t('重要')}}</el-radio>
            <el-radio label="minor" class="minor">{{$t('次要')}}</el-radio>
            <el-radio label="warning" class="warning">{{$t('提示')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('告警声音开关')" prop="voice">
          <el-radio-group v-model="record.voice" :disabled='record.state === "disable"'>
            <el-radio label="on" class="on">{{$t('开')}}</el-radio>
            <el-radio label="off" class="off">{{$t('关')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('告警信息发送方式')" prop="method">
          <el-radio-group v-model="record.method" :disabled='record.state === "disable"'>
            <el-radio label="none" class="none">{{$t('无')}}</el-radio>
            <el-radio label="smtp" class="smtp">SMTP</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('告警接收者')" prop="reciver">
          <el-input v-emoji v-model="record.reciver" ref="reciver" :disabled='record.state === "disable" || record.method === "none"' style="width:272px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('告警时间间隔')" prop="interval" v-if="record.name !== 'sys-manager' && record.name !== 'interface'">
          <el-input v-emoji v-model="record.interval" ref="interval" :disabled='record.state === "disable"' style="width:272px;" size='small'></el-input>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="apiDialogVisible(record.interfaces)" size="small" v-if="record.name === 'interface'">{{$t('添加接口')}}</el-button>
      <el-table size='mini' ref="multipleTable" border :data="record.interfaces" tooltip-effect="dark" v-if="record.name === 'interface'" style="width: 100%;margin-top:10px;">
        <el-table-column prop="strPhysicsName" :label="$t('接口名称')" align='center' min-width="100">
          <template slot-scope="scope">
            <tooltip :copyText="scope.row.strPhysicsName" class="wid190">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="150">
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="deleteInterfaces(scope.$index)">{{$t('删除')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
    <sys-api-dialog v-if="addApiDialogVisible" ref="refAddApiDialogVisible" @addApi='addApi'></sys-api-dialog>
  </el-dialog>
</template>
<script>
import { setSysAlert } from '@/api/system/alarm/strategy'
import SysApiDialog from './SysApiDialog.vue'
import { inputClass } from '@/utils/input-class.js'
export default {
  components: { SysApiDialog },
  name: 'SysDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateReciver = (rule, value, callback) => {
      let email = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (value === '') {
        callback()
      } else if (email.test(value)) {
        callback()
      } else {
        callback(new Error(this.$t('请输入邮箱格式')))
      }
    }
    return {
      dialogVisible: false,
      addApiDialogVisible: false,
      lang: this.$i18n.locale,
      record: {
        name: '',
        state: 'disable',
        threshold: '',
        severity: 'warning',
        voice: 'off',
        method: 'none',
        interfaces: [],
        reciver: '',
        interval: ''
      },
      recordCopy: {
        name: '',
        state: 'disable',
        threshold: '',
        severity: 'warning',
        voice: 'off',
        method: 'none',
        interfaces: [],
        reciver: '',
        interval: ''
      },
      modeNameArray: {
        'cpu': 'CPU',
        'memory': '内存',
        'disk-space': '硬盘空间',
        'interface': '接口链路状态',
        'sys-manager': '设备管理'
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        state: [{ required: false, validator: validateName, trigger: 'blur' }],
        threshold: [{ required: false, validator: validateName, trigger: 'blur' }],
        severity: [{ required: false, validator: validateName, trigger: 'blur' }],
        voice: [{ required: false, validator: validateName, trigger: 'blur' }],
        method: [{ required: false, validator: validateName, trigger: 'blur' }],
        reciver: [{ required: false, validator: validateReciver, trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      if (data) {
        this.record = Object.assign(this.record, data)
        this.record.method = data['alarm-method']
        this.record.voice = data['alarm-voice']
        this.record.name = data['mode-name']
        this.record.interfaces = []
        if (data.interfaces) {
          data.interfaces.forEach(item => {
            this.record.interfaces.push({ strPhysicsName: item })
          })
        }
        this.$nextTick(() => {
          const data = ['reciver']
          inputClass(this.$refs, data)
          if (!['sys-manager', 'interface'].includes(this.record.name)) {
            inputClass(this.$refs, ['threshold', 'interval'])
          }
        })
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.record))
          let interList = []
          formData.interfaces.forEach(item => {
            interList.push(item.strPhysicsName)
          })
          formData.interfaces = interList
          setSysAlert(formData).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t(res.msg),
                type: 'success'
              })
              this.close()
              this.$parent.listData()
            }
          })
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    changeSelect (data) {
      this.record.port = this.encryptionPort[data]
    },
    // 编辑按钮表单
    apiDialogVisible (data) {
      this.addApiDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refAddApiDialogVisible.init(data)
      })
    },
    addApi (data) {
      var beList = []
      this.record.interfaces.forEach(item => {
        beList.push(item.strPhysicsName)
      })
      data.forEach(item => {
        if (!beList.includes(item.strPhysicsName)) {
          this.record.interfaces.push(item)
        }
      })
    },
    deleteInterfaces (index) {
      this.record.interfaces.splice(index, 1)
    }
  }
}
</script>
